package com.wisewin.circle.service;

import com.wisewin.circle.entity.db.TrendCommentDO;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class TrendCommentNodeBuilder {
    private List<TrendCommentDO> pmList;
    public TrendCommentNodeBuilder(List<TrendCommentDO> pmList) {
        this.pmList = pmList;
    }

    //建立树形结构
    public List<TrendCommentDO> builTree() {
        List<TrendCommentDO> treeMenus = new ArrayList<>();
        for (TrendCommentDO menuNode : getRootNode()) {
            List<TrendCommentDO> children = new ArrayList<>();
            buildChilTree(menuNode, children);
            menuNode.setChildren(CollectionUtils.isEmpty(children) ? null : children);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private TrendCommentDO buildChilTree(TrendCommentDO pNode, List<TrendCommentDO> children) {
        for (TrendCommentDO pmNode : pmList) {
            if (pmNode.getParentId().equals(pNode.getCommentId())) {
                children.add(pmNode);
                buildChilTree(pmNode, children);
            }
        }
        return pNode;
    }

    //获取所有根节点
    private List<TrendCommentDO> getRootNode() {
        List<TrendCommentDO> rootList = new ArrayList<>();
        for (TrendCommentDO node : pmList) {
            String parentId = node.getParentId().toString();
            if (StringUtils.isEmpty(parentId) || parentId.equals("0")) {
                rootList.add(node);
            }
        }
        return rootList;
    }
}
